package com.sq.util.encrypt;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sq.util.ByteUtil;
import com.sq.util.exception.CommonException;

//* 密钥产生
//* 1私钥
//* openssl genrsa -out rsa_private_key.pem 1024 
//* 2公钥
//* openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout
//* 3私钥转换一下
//* openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt 
//* 4利用RSAEncryptDemo产生公钥的和私钥的16进制字符串
/**
 * 
 * @author sq
 */
public class Rsa {
    private static final Logger log = LoggerFactory.getLogger(Rsa.class);

    public static final String ALGORITHM = "RSA";

    public static Key genKey() {
        return SignUtil.genRsaKey();
    }

    /**
     * 加密
     */
    public static byte[] encrypt(byte[] data, String hexPublicKey) {
        return encrypt(data, ByteUtil.toBytes(hexPublicKey));
    }

    /**
     * 加密
     */
    public static byte[] encrypt(byte[] data, byte[] publicKey) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey);
            PublicKey key = keyFactory.generatePublic(x509KeySpec);
            // 数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new CommonException("加密出错:" + e.getMessage());
        }
    }

    /**
     * 加密
     */
    public static byte[] decrypt(byte[] data, String hexPrivateKey) {
        return decrypt(data, ByteUtil.toBytes(hexPrivateKey));
    }

    /**
     * 解密
     */
    public static byte[] decrypt(byte[] data, byte[] privateKey) {
        try {
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
            PrivateKey key = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new CommonException("解密出错:" + e.getMessage());
        }
    }

}